import Vue from "vue";
import VueRouter from "vue-router";
import routes from './routes';
import store from '@/store';
import { Message, Loading } from 'element-ui';
import activeRoutes from './activeRoutes';

Vue.use(VueRouter);

const router = new VueRouter({
    mode: 'hash',
    routes
});

/* 全局前置守卫 */
let LoadingIns;
router.beforeEach(async (to, from, next) => {
    // 登录态校验
    let profile = store.state.profile;
    if (!profile && to.path !== '/login' && to.meta.title !== '404') {
        // 开启loading效果，防止白屏等待
        LoadingIns = Loading.service({
            background: 'rgba(0,0,0,0.7)',
            text: '小主，奴家正在努力加载中...'
        });
        profile = await store.dispatch('setProfileAsync');
        if (!profile) {
            // 当前用户是没有登录的:跳转到登录页，并且传递目标地址
            Message.error('您还未登录，请您先登录!');
            next(`/login?to=${to.path}`);
            return;
        }
    }
    next();
});

/* 全局后置守卫 */
router.afterEach(to => {
    // 修改页面的title
    let { title } = to.meta;
    document.title = title ? `新蜂CMS系统-${title}` : `新蜂CMS系统`;

    // 关闭loading
    if (LoadingIns) LoadingIns.close();
});

/* onReady:事件只会触发一次「页面刷新或者第一次加载触发，后期路由切换中不触发」 */
router.onReady(to => {
    if (to.path === '/login') return;
    activeRoutes(router);
});

export default router;